//
//  APGuideViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/3.
//

#import "APGuideViewController.h"
#import "APGuideView.h"
#import "AppDelegate.h"
#import "APLoginViewController.h"

@interface APGuideViewController ()<APGuideViewdelegate>
@property (nonatomic, strong) APGuideView *guideView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) bool hasJump;
@end

@implementation APGuideViewController

- (APGuideView *)guideView{
    if (!_guideView) {
        _guideView = [[APGuideView alloc] init];
        _guideView.delegate = self;
    }
    return _guideView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _hasJump = false;
    [self.view addSubview:self.guideView];
    [self.guideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self createTimer];
}

- (void)didRepeat{
    NSInteger currentPage = self.guideView.currentPage;
    LYLog(@"-----------%zd-----------------",currentPage);
    if (currentPage < 2) {
        [self.guideView goPage:currentPage + 1];
    }else{
        [_timer invalidate];
        _timer = nil;
        if (_hasJump) {
            return;
        }
        _hasJump = true;
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        if (![app.window.rootViewController isKindOfClass:[APLoginViewController class]]) {
            app.window.rootViewController  = [[APLoginViewController alloc] init];
        }
    }
}

- (void)guideView:(APGuideView *)guideView didSelectedItem:(NSIndexPath *)indexPath{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(createTimer) object:nil];
    [_timer invalidate];
    _timer = nil;
    [self didRepeat];
    [self performSelector:@selector(createTimer) withObject:nil afterDelay:2];
}

- (void)guideViewDidEndDragging:(APGuideView *)guideView{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(createTimer) object:nil];
    [_timer invalidate];
    _timer = nil;
    [self performSelector:@selector(createTimer) withObject:nil afterDelay:2];
}

- (void)createTimer{
    [_timer invalidate];
    _timer = nil;
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(didRepeat) userInfo:nil repeats:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}



- (void)dealloc{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

@end
